package com.springboot.scheduled.dynamic.cron;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;

/**
 * 动态修改 cron 的定时器配置
 */
//@EnableScheduling
//@Component
public class TaskCronChangeConfigure implements SchedulingConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(TaskCronChangeConfigure.class);

    private static String cron = "0/3 * * * * *"; // 该值也可转为从该数据库后续对应的数据

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {

        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                // 业务处理逻辑
                logger.info("动态的 corn 定时器，now={}", LocalDateTime.now());
            }
        };

        Trigger trigger = new Trigger() {
            @Override
            public Date nextExecutionTime(TriggerContext triggerContext) {
                // 可在此处从数据库中获取 cron值，根据数据库中的值执行
                // 触发任务时，根据cron修改执行周期
                CronTrigger cronTrigger = new CronTrigger(cron);
                return cronTrigger.nextExecutionTime(triggerContext);
            }
        };

        scheduledTaskRegistrar.addTriggerTask(runnable, trigger);
    }

    public static String getCron() {
        return cron;
    }

    public static void setCron(String cron) {
        TaskCronChangeConfigure.cron = cron;
    }
}
